package com.hns.phone.base.web;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hns.can.common.domain.ReturnResult;
import com.hns.can.common.web.BaseController;
import com.hns.phone.base.service.PhoneVrsnService;
import com.hns.phone.base.vo.UpgPhoneVrsn;
import com.hns.tool.pub.FTPUtils;

/**
 * @ClassName: PhoneSetupInfoController
 * @Description:
 * @author zhangl
 * @email victor_007@126.com
 * @date 2016年11月18日 下午6:43:00
 */
@Controller
@RequestMapping("/api/phoneSetupInfo")
public class PhoneSetupInfoController extends BaseController {

    @Autowired
    private PhoneVrsnService phoneVrsnService;

    /**
     * @Title: checkVersion
     * @Description: 获取最新版本
     * @param type
     * @return
     * @throws Exception Object
     */
    @RequestMapping("/checkVersion")
    @ResponseBody
    public Object checkVersion() throws Exception {
        Map<String, Object> params = getParameter_prefix();
        Map map = phoneVrsnService.getUpgPhoneVrsn(params);
        return this.getReturnResult(map);
    }

    /**
     * @Title: downloadFile
     * @Description: 文件下载
     * @throws Exception void
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response) throws Exception {
        Map<String, Object> params = getParameter_prefix();
        Map map = phoneVrsnService.getUpgPhoneVrsn(params);
        String remoteFile = "";
        FTPClient ftpClient = FTPUtils.getInstance().getClient();
        OutputStream out = null;
        if (map != null) {
            remoteFile = map.get("UPGFILE").toString();
            try {
                InputStream inputStream = ftpClient.retrieveFileStream(new String(remoteFile.getBytes(), "ISO-8859-1"));
                if(inputStream != null){
                    out = response.getOutputStream();
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    inputStream.close();
                    out.flush();
                }
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }
}
